package com.sigmazero13.bgjeeves;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Process;

public class GameTimerService extends Service {
	private final IBinder mBinder = new LocalBinder();
	private long elapsedTime = 0;
	private long startTime = 0;
	private String gameName = "Game";
	private boolean running = false;
	private static final int TIMER_NOTIFICATION_ID = 1313;
	private Timer refreshTimer;
	
	public class LocalBinder extends Binder {
		GameTimerService getService() {
			return GameTimerService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		startService(intent);
		return mBinder;
	}

	@Override
	public void onCreate() {
		// Start up the thread running the service. Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block. We also make it
		// background priority so CPU-intensive work will not disrupt our UI.
		HandlerThread thread = new HandlerThread("TimerThread", Process.THREAD_PRIORITY_BACKGROUND);
		thread.start();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		
		return START_STICKY;
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		if (!running) {
			stopSelf();
		}
		return false;
	}

	private Notification getNotification() {
		int icon = R.drawable.bgjeeves_notification;
		CharSequence text = gameName + " Started";
		long when = System.currentTimeMillis();
		Notification n = new Notification(icon, text, when);

		Context context = getApplicationContext();
		CharSequence contentTitle = "B.G. Jeeves - " + gameName;
		long minutes = getElapsedSeconds()/60;
		CharSequence contentText = "Playing Time: " + minutes + " minute" + (minutes == 1?"":"s");
		if (!running) contentText = "*PAUSED* " + contentText;
		n.flags = Notification.FLAG_ONGOING_EVENT;

		Intent notificationIntent = new Intent(this, GameTimerView.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		n.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

		return n;
	}

	private void setNotification() {
		Notification n = getNotification();

		startForeground(TIMER_NOTIFICATION_ID, n);
	}

	private void updateNotification() {
		if (startTime == 0 && elapsedTime == 0)
			return;

		Notification n = getNotification();

		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		mNotificationManager.notify(TIMER_NOTIFICATION_ID, n);
	}

	private void stopNotification() {
		stopForeground(true);
	}

	public void startTimer() {
		startTime = System.currentTimeMillis();
		running = true;
		setNotification();
		refreshTimer = new Timer("GameTimer");
		refreshTimer.scheduleAtFixedRate(new TimerTask() {
				@Override
				public void run() {
					updateNotification();
				}
			}, 1000, 30000);
	}

	public void stopTimer() {
		if (startTime == 0)
			return;
		long stopTime = System.currentTimeMillis();
		elapsedTime += stopTime - startTime;
		startTime = 0;
		running = false;
		
		if (refreshTimer != null) {
			refreshTimer.cancel();
			refreshTimer.purge();
			refreshTimer = null;
		}
		
		updateNotification();
	}

	public void resetTimer() {
		if (refreshTimer != null) {
			refreshTimer.cancel();
			refreshTimer.purge();
			refreshTimer = null;
		}
		
		startTime = 0;
		elapsedTime = 0;
		running = false;
		stopNotification();
	}
	
	public boolean isRunning() {
		return running;
	}

	public long getElapsedSeconds() {
		long et = elapsedTime;
		if (running) {
			et += System.currentTimeMillis() - startTime;
		}
		
		return et / 1000;
	}
	
	public void setGameName(String gameName) {
		if (gameName == null) gameName = "";
		gameName = gameName.trim();
		if (gameName.equals("")) gameName = "UNKNOWN GAME";
		
		this.gameName = gameName;
		updateNotification();
	}

}
